package com.misyi.designpattern.builder;

/**
 * 构造器模式
 *
 * @author licong
 * @date 2021-09-11 下午11:32
 */
public class BuilderPatternDemo {

    public static void main(String[] args) {
        Product product = new ProductBuilder()
                .field1("值1")
                .field2("值2")
                .field3("值3")
                .get();
        System.out.println(product);

        // 复杂对象的构建过程太复杂了
        // 如果每个客户端自己去构建的话, 代码太冗余, 可维护性差
        // new ProductBuilder() 的过程, 可以利用简单工厂模式, 所有的构建完全替换掉
    }


    public interface Builder {
        Builder field1(String value);
        Builder field2(String value);
        Builder field3(String value);
    }


    public static class ProductBuilder implements Builder {
        private final Product product = new Product();

        public Product get() {
            return product;
        }


        @Override
        public ProductBuilder field1(String value) {
            System.out.println("在设置field1之前进行复杂的校验逻辑");
            product.setField1(value);
            return this;
        }

        @Override
        public ProductBuilder field2(String value) {
            System.out.println("在设置field2之前进行复杂的数据格式转换逻辑");
            product.setField2(value);
            return this;
        }

        @Override
        public ProductBuilder field3(String value) {
            System.out.println("在设置field3之前进行复杂的数据处理逻辑, 跟其他对象进行关联");
            product.setField3(value);
            return this;
        }
    }


    public static class Product {
        private String field1;

        private String field2;

        private String field3;

        public String getField1() {
            return field1;
        }

        public void setField1(String field1) {
            this.field1 = field1;
        }

        public String getField2() {
            return field2;
        }

        public void setField2(String field2) {
            this.field2 = field2;
        }

        public String getField3() {
            return field3;
        }

        public void setField3(String field3) {
            this.field3 = field3;
        }


        @Override
        public String toString() {
            return "Product{" +
                    "field1='" + field1 + '\'' +
                    ", field2='" + field2 + '\'' +
                    ", field3='" + field3 + '\'' +
                    '}';
        }
    }
}
